/**
 * Created by chenzheyu on 2017/4/5.
 */

$(function () {
    var CtiyInput = $('#city');
    var countyInput = $('#county');
    var provincialInput = $('#provincial');
    var siteInput = $('input[name="site"]');
    var latInput = $('.AddStore .latitude');
    var lngInput = $('.AddStore .longitude');
    var companyId = '';
    var companyName = '';
    var imagesUrl=[];

    $.ajax({
        url:ctx+'/company/listAllData',
        type: 'GET',
        success: function (data) {

            var DownPullSelectOption = {
                    data: [],
                    onChange: function (e) {
                        companyId = e.val;
                        companyName = e.text;
                    }
                }
            ;
            for (var i = 0; i < data.length; i++) {
                (function () {
                    var index = i;
                    DownPullSelectOption.data.push({
                        name: data[index].abbreviation,
                        Val: data[index].id
                    });
                })()
            }

            $('.SubordinateCompany').DownPullSelect(DownPullSelectOption);
        }
    });
    provincialInput.on('blur', function () {
    });
    CtiyInput.on('blur', function () {
        var CtiyInputVal = CtiyInput.val();
        if (countyInput.val()) {
            CtiyInputVal = countyInput.val();
        }

        Map(CtiyInputVal, 10)

    });
    countyInput.on('blur', function () {
        var CtiyInputVal = countyInput.val();
        Map(CtiyInputVal, 13)

    });
    siteInput.on('blur', function () {
        var CtiyInputVal = countyInput.val();
        var siteInputVal = siteInput.val();
        Map(CtiyInputVal, 20, siteInputVal)
    });
    Map('北京', 10, '东城区');
    function Map(City, Grade, locals) {
        // 百度地图API功能
        var map = new BMap.Map("StoreMap");    // 创建Map实例
        map.centerAndZoom(City || '北京', Grade);  // 初始化地图,设置中心点坐标和地图级别
        map.setCurrentCity(City || '北京');          // 设置地图显示的城市 此项是必须设置的
        map.enableScrollWheelZoom(true);

        if (locals) {
            var local = new BMap.LocalSearch(map, {
                renderOptions: {map: map}
            });
            local.search(locals);


            local.setInfoHtmlSetCallback(function (poi, html) {//搜索完成后的回掉函数
                var point = new BMap.Point(poi.marker.point.lng, poi.marker.point.lat);
                var geoc = new BMap.Geocoder();
                geoc.getLocation(point, function (rs) {
                    var PT = rs.point;
                    geoc.getLocation(PT, function (rs) {//通过经纬度解析详细地址
                        var addComp = rs.addressComponents;
                        CtiyInput.val(addComp.city);
                        countyInput.val(addComp.city);
                        provincialInput.val(addComp.province);
                        siteInput.val(addComp.street + addComp.streetNumber);
                        latInput.text(PT.lat);
                        lngInput.text(PT.lng);
                    })
                });
            });
        };

        map.addEventListener("click", function (e) {
            if (e.overlay) {
                var geoc = new BMap.Geocoder();
                var pt = e.point;
                geoc.getLocation(pt, function (rs) {
                    var addComp = rs.addressComponents;
                    CtiyInput.val(addComp.city);
                    countyInput.val(addComp.city);
                    provincialInput.val(addComp.province);
                    siteInput.val(addComp.street + addComp.streetNumber);
                    latInput.text(pt.lat);
                    lngInput.text(pt.lng);
                });
            }
        });

        var menu = new BMap.ContextMenu();
        var txtMenuItem = [
            {
                text: '选择该点',
                callback: function (p) {
                    map.clearOverlays();
                    var memberMarker = new BMap.Marker(p);  // 创建标注
                    map.addOverlay(memberMarker);
                    var gc = new BMap.Geocoder();
                    gc.getLocation(p, function (rs) {
                        var addComp = rs.addressComponents;
                        $("#provincial option").each(function (index, element) {
                            if ($(element).attr("value") == addComp.province) {
                                $(element).attr("selected", "selected");
                                updateMap = false;
                                $(element).change();
                                return false;
                            }
                        });
                        $("#city option").each(function (index, element) {
                            if ($(element).attr("value") == addComp.city) {
                                $(element).attr("selected", "selected");
                                updateMap = false;
                                $(element).change();
                                return false;
                            }
                        });
                        $("#county option").each(function (index, element) {
                            if ($(element).attr("value") == addComp.district) {
                                $(element).attr("selected", "selected");
                                updateMap = false;
                                $(element).change();
                                return false;
                            }
                        });

                        $(".latitude").text(p.lat);
                        $(".longitude").text(p.lng);

                        var geoc = new BMap.Geocoder();
                        geoc.getLocation(p, function (rs) {
                            var addComp = rs.addressComponents;
                            // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                            $('#provincial').val(addComp.province);
                            $('#city').val(addComp.city);
                            $('#county').val(addComp.district);
                            $('#street').val(addComp.street + addComp.streetNumber);
                        });
                    })

                }
            }
        ];
        for (var i = 0; i < txtMenuItem.length; i++) {
            menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
        }
        map.addContextMenu(menu);

    }


    var option = {
        DefaultImage:[],
        UpLimit: 10,
        url: fileUploadUrl,
        onChange: function (e) {
            imagesUrl=e.join("&:&");
        }
    };
    $('.Action').UpLoading(option);

    $('.OK').on('click', function () {
        var OptionData = {
            companyId: companyId,
            companyName: companyName,
            shopName: '',
            address: '',
            lat: '',
            lng: '',
            serviceRange: '',
            contacts: '',
            phone: '',
            telephone: '',
            email: '',
            memo: '',
            image: imagesUrl,
            city:''
        };
        if ($('.shopName').val()) {
            OptionData.shopName = $('.shopName').val();

            if ($('.longitude').text()) {
                OptionData.lng = $('.longitude').text();

                if ($('.latitude').text()) {
                    OptionData.lat = $('.latitude').text();

                    if ($('.serviceRange').val()>0 ) {
                        OptionData.serviceRange = $('.serviceRange').val();

                        if ($('.contacts').val()) {
                            OptionData.contacts = $('.contacts').val();
                            if ( (/^1[34578]\d{9}$/.test($('.phone').val())) || /^0\d{2,3}-\d{7,8}(-\d{1,6})?$/.test($('.telephone').val())) {
                                OptionData.phone = $('.phone').val();


                                    OptionData.telephone = $('.telephone').val();

                                    if (/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test($('.email').val()) ||OptionData.email =='') {
                                        OptionData.email = $('.email').val();
                                        OptionData.memo = $('.memo').val()||'';
                                        OptionData.address=$('.address').val();
                                        OptionData.city=$('#city').val();
                                        $.ajax({
                                            url: ctx+'/rentshop/insertRentshop',
                                            data: OptionData,
                                            type: 'POST',
                                            success: function (data) {

                                                if(data.message=='创建成功'){
                                                	 new $().Overlays({data:{text:'添加成功，即将跳转！',state:'Ok'}});
                                                	 setTimeout(function(){
                                                		 window.location.href=ctx+"/rentshop/rentshoplist";
                                                	 },1500)                                                   
                                                }else{
                                               	 	new $().Overlays({data:{text:'添加失败！',state:'No'}});
                                                }
                                            }
                                        })
                                    } else {
                                	 	new $().Overlays({data:{text:'请输入正确邮箱！',state:'No'}});
                                        return
                                    }
                            } else {
                                new $().Overlays({data:{text:'请输入联系人手机和或座机号！',state:'No'}});
                                return
                            }

                        } else {
                            new $().Overlays({data:{text:'请输入联系人！',state:'No'}});
                            return
                        }
                    } else {
                        new $().Overlays({data:{text:'请输入可配送范围！并且必须大于0',state:'No'}});
                        $('.serviceRange').val('')
                        return
                    }
                } else {
                    new $().Overlays({data:{text:'定位失败！',state:'No'}});
                    return
                }
            } else {
                new $().Overlays({data:{text:'定位失败！',state:'No'}});
                return
            }
        } else {
            new $().Overlays({data:{text:'请输入门店名称！',state:'No'}});
            return
        }

    });
    $('.Cancel').on('click',function () {
        window.location.href=ctx+"/rentshop/rentshoplist";
    });

    new PCAS('provincial','city','county');

});

